package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.query.EmployeeQueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo){
        PageResult<Employee> result = employeeService.query(qo);
        System.out.println(result);
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments",departments);
        model.addAttribute("pageResult",result);
        return "employee/list";
    }
    @RequestMapping("/input")
    public String input(Long id,Model model){
        System.out.println(id);
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments",departments);
        List<Role> roles = roleService.listAll();
        model.addAttribute("roles",roles);
        if(id != null){
            Employee employee = employeeService.get(id);
            model.addAttribute("employee",employee);
        }
        return "employee/input";
    }
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee employee){
        System.out.println(employee);
        if(employee.getId() == null){
            employeeService.save(employee);
        }else{
            System.out.println(employee);
            employeeService.update(employee);
        }
        return "redirect:/employee/list.do";
    }
    @RequestMapping("/delete")
    public String delete(Long id){
        if(id != null){
            employeeService.delete(id);
        }
        return "redirect:/employee/list.do";
    }
}
